<template>
    <div>
      <h1>用户管理</h1>
      <el-row>
        <el-col :span="10">
          <el-input v-model="searchText" placeholder="搜索用户"></el-input>
        </el-col>
        <el-col :span="4" :offset="10">
          <el-button type="primary" @click="addUserDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <br>
      <el-table :data="displayedUsers" style="width: 100%">
        <el-table-column prop="name" label="姓名"></el-table-column>
        <el-table-column prop="phone" label="电话"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="address" label="地址"></el-table-column>
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button type="primary" @click="editUserDialogVisible = true; currUser = row">编辑</el-button>
            <el-button type="danger" @click="deleteUser(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <br>
      <el-pagination :total="users.length" :page-size="pageSize" @current-change="handleCurrentChange"></el-pagination>
      <el-dialog :visible.sync="addUserDialogVisible" title="添加用户" @close="resetAddUserForm">
        <el-form ref="addUserForm" :model="addUserForm" label-width="100px" :rules="addUserFormRules">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="addUserForm.name"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="phone">
            <el-input v-model="addUserForm.phone"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addUserForm.email"></el-input>
          </el-form-item>
          <el-form-item label="地址" prop="address">
            <el-input v-model="addUserForm.address"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer">
          <el-button @click="addUserDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addUser">确定</el-button>
        </div>
      </el-dialog>
      <el-dialog :visible.sync="editUserDialogVisible" title="编辑用户" @close="resetEditUserForm">
        <el-form ref="editUserForm" :model="currUser" label-width="100px" :rules="editUserFormRules">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="currUser.name"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="phone">
            <el-input v-model="currUser.phone"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="currUser.email"></el-input>
          </el-form-item>
          <el-form-item label="地址" prop="address">
            <el-input v-model="currUser.address"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer">
          <el-button @click="editUserDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="editUser">确定</el-button>
        </div>
      </el-dialog>
    </div>
  </template>
  
<script>
import axios from 'axios';
  export default {
    name: "userlist",
    data() {
      return {
        searchText: '',
        pageSize: 10,
        currentPage: 1,
        addUserDialogVisible: false,
        editUserDialogVisible: false,
        addUserFormRules: {
          name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
          phone: [{ required: true, message: '请输入电话', trigger: 'blur' }],
          email: [{ required: true, message: '请输入邮箱', trigger: 'blur' }],
          address: [{ required: true, message: '请输入地址', trigger: 'blur' }],
        },
        editUserFormRules: {
          name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
          phone: [{ required: true, message: '请输入电话', trigger: 'blur' }],
          email: [{ required: true, message: '请输入邮箱', trigger: 'blur' }],
          address: [{ required: true, message: '请输入地址', trigger: 'blur' }],
        },
        addUserForm: {
          name: '',
          phone: '',
          email: '',
          address: '',
        },
        currUser: {},
        users: [],
      };
    },
    computed: {
      displayedUsers() {
        return this.users.filter(user => user.name.includes(this.searchText)).slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize);
      },
    },
    mounted() {
      axios.get('http://localhost:3000/userslist')
        .then(response => {
          this.users = response.data;
          console.log(response.data);
        })
        .catch(error => {
          console.error(error);
        });
        
    },
    methods: {
      handleCurrentChange(newPage) {
        this.currentPage = newPage;
      },
      resetAddUserForm() {
        this.$refs.addUserForm.resetFields();
        this.addUserForm = {
          name: '',
          phone: '',
          email: '',
          address: '',
        };
      },
      addUser() {
        this.$refs.addUserForm.validate(valid => {
          if (valid) {
            this.users.push({ ...this.addUserForm });
            this.addUserDialogVisible = false;
            this.resetAddUserForm();
            console.log(  this.users.slice(-1)[0]   );  
            const data = this.users.slice(-1)[0];
            console.log(JSON.stringify(data));
           axios.post('http://localhost:3000/usersadd',data)
  .then(response => {
    if (response.status === 200) {
      alert('Data saved successfully');
    } else {
      throw new Error('Error saving data');
    }
  })
  .catch(error => {
    console.error(error);
    alert('Error saving data');
  })
          }
        });
      },
      resetEditUserForm() {
        this.$refs.editUserForm.resetFields();
      },
//修改数据
      editUser() {
        this.$refs.editUserForm.validate(valid => {
          if (valid) {
      // 获取修改后的数据
      const editedUser = {
        name: this.currUser.name,
        phone:this.currUser.phone,
        email: this.currUser.email,
        address:this.currUser.address,
      };

      axios.put('http://localhost:3000/userchange', editedUser)
        .then(response => {
          console.log('User updated', response.data);
        })
        .catch(error => {
          console.error('Error updating user', error);
        });
      console.log(editedUser);
      // 关闭对话框
      this.editUserDialogVisible = false;
    }
        });
        axios.get('http://localhost:3000/userslist')
        .then(response => {
          this.users = response.data;
          console.log(response.data);
        })
        .catch(error => {
          console.error(error);
        });
      },
      deleteUser(user) {
        console.log(user);
        const index = this.users.indexOf(user);
        if (index >= 0) {
          this.users.splice(index, 1);
        }
        axios.delete('http://localhost:3000/userdelete', { params: { user} });
      },
    },
  };
  </script>